from flask import Blueprint,request,make_response,jsonify,redirect
from flask_restful import Resource,Api
from utils.captcha.captcha import captcha
from utils.Myredis import r
import json
from utils.comm import send_message
import requests
import random
from application.models.users.user import *
from application.models.users.user import db
import time
from utils.Myjwt import myjwt
login_blue=Blueprint("login",__name__)
api=Api(login_blue)
# 获取图片验证码
@login_blue.route("/getimg")
def getimg():
    # 调用captcha生成图片验证码
    name,text,img=captcha.generate_captcha()
    # 存入redis字符串 key:uuid value:text
    uuid=request.args.get("uuid")
    # 存入redis
    r.str_setex(uuid,text,300)
    res=make_response(img)
    # 以流的方式生成图片验证码
    res.headers["Content-Type"]="image/jpg"
    return res
# 发送短信验证码
@login_blue.route("/sms",methods=["POST"])
def sms():
    # 获取参数
    data=json.loads(request.data)
    mobile=data["mobile"]
    uuid=data["uuid"]
    imagecode=data["imagecode"]
    if not all([mobile,uuid,imagecode]):
        return jsonify({"code":401,"msg":"参数不完整"})
    # 验证图片验证码
    code=r.get_str(uuid)
    # 通过uuid从redis取出来和传递过来的参数进行对比，全部转为小写
    if code:
        if imagecode.lower()==code.lower().decode():
            # 验证一分钟之内只能发送一次
            mcode=r.get_str(mobile)
            if mcode:
                return jsonify({"code":403,"msg":"一分钟只能发送一次"})
            # 生成随机数
            scode=str(random.randint(1000,9999))
            print(scode)
            # 调用短信平台
            flag=send_message(mobile,scode)
            print('.......asddddddddd',flag)
            # if flag==True:
            # 存入redis
            r.add_str(mobile,scode)
            # 清除redis中的图片验证码
            r.del_key(uuid)
            # 返回结果
            return jsonify({"code": 200, "msg": "发送成功"})
            # else:
            #     return jsonify({"code": 403, "msg": "发送验证码失败"})
        else:
            return jsonify({"code":402,"msg":"图片验证码不正确"})
        # 失败返回错误信息
    else:
        return jsonify({"code":403,"msg":"验证码不存在"})

# 登陆
@login_blue.route("/login",methods=["POST"])
def login():
    # 获取参数
    data=json.loads(request.data)
    if data:
        mcode=data["mcode"]
        mobile=data["mobile"]
        # 根据手机号去redis获取验证码
        code=r.get_str(mobile)
        print("rrrrrrr",code)
        if code:
            # 验证码是否相同
            if int(code)==int(mcode):
                # 如果相同查询数据库user表，存在返回信息
                u=User.query.filter(User.mobile==mobile).first()
                if u:
                    # 删除redis中的验证码
                    r.del_key(mobile)
                # 不存在写入用户表
                else:
                    u=User(mobile=mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                token = myjwt.jwt_encode({"data": {"userid": u.id ,"mobile": u.mobile, "exptime": int(time.time())}})
                return jsonify({"code": 200, "msg": "登陆成功","token":token,"userid":u.id})
            else:
                return jsonify({"code":201,"msg":"验证码错误"})
        else:
            return jsonify({"code":200,"msg":"验证码过期"})


# 装饰器
# 权限认证
# def islogin(func):
#     @functools.wraps(func)
#     def wrapper():
#         func()
#         # 权限验证判断,如果有问题返回
#         return func()
#     return wrapper
# def islogin(type):
#     def pemistion(func):
#         @functools.wraps(func)
#         def wrapper():
#             func()
#             if type == 1:
#                 return redirect("http://www.baidu.com")
#             else:
#                 return redirect("http://www.jd.com")
#         return wrapper
#     return pemistion

# 测试
@login_blue.route("/cart")
# @islogin(2)
def cart():
    print("执行cart")
    return jsonify({"code": 200, "msg": 'msg'})
@login_blue.route('/tiao')
def tiao():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    # 微博平台地址
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s" % (
    client_id, redirect_uri)
    return jsonify({'code':200,'url':url})


# 设置回调地址
@login_blue.route('/user/weiboCallback/')
def hui():
    code = request.args.get('code')
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token',data=data)
    #获取token和uid
    message = json.loads(res.text)
    print('666',message)
    token = message['access_token']
    uid = message['uid']
    #判断表中是否有数据
    u = db.session.execute("select user.id,user.mobile from sf_login inner join user on sf_login.userid=user.id where sf_login.uid='%s'"%(str(uid)))
    # sql = "select user.id,user.mobile  from sf_login inner join user on sf_login.userid=user.id where sf_login.uid='%s'"%(str(uid))
    # user = db.fetchone(sql)
    user = list(u)
    if user:
        for i in user:
            print('i',i)
            token = myjwt.jwt_encode(
                data ={'data':{'uid':i[0],'mobile':i[1],'exp':int(time.time())}}
            )
            return redirect("http://localhost:8080/#/login?token=" + token + "&uid=" + str(i[1]))
    else:
        print(token)
        return redirect("http://localhost:8080/#/bang?token=" + str(token) + "&uid=" + str(uid))

@login_blue.route('/bang',methods=['POST'])
def bang():
    data = json.loads(request.data)
    #判断手机号是否存在用户表
    user = User.query.filter_by(mobile=data['mobile']).first()
    if user:
        #加入三方登录表
        sf = SfLogin(userid=user.id,webfrom='weibe',uid=data['uid'],token=data['token'])
        db.session.add(sf)
        db.session.commit()
        data = {"data": {"userid": user.id, "mobile": user.mobile, "exptime": int(time.time())}}
        token = myjwt.jwt_encode(data)
        return jsonify({"code": 200, "msg": "登录成功", "token": token, "userid": user.id, "mobile": user.mobile})
    else:
        # 加入用户表
        admin = User(mobile=data["mobile"],password=data['password'],nikename=158399)
        userid = db.session.add(admin)
        # 加入三方登录表
        sf = SfLogin(userid=userid, webfrom="weibo", uid=data["uid"], token=data["token"])
        db.session.add(sf)
        db.session.commit()
        # 生成token
        data = {"data": {"userid": userid, "mobile": admin.mobile, "exptime": int(time.time())}}
        token = myjwt.jwt_encode(data)
        return jsonify({"code": 200, "msg": "登录成功", "token": token, "userid": userid, "mobile": admin.mobile})




